package org.teremail.message;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.teremail.panto.ContentDisposition;
import org.teremail.panto.ContentHeader;
import org.teremail.panto.ContentTransferEncoding;
import org.teremail.panto.ContentType;
import org.teremail.store.Strings;

import com.google.common.collect.ImmutableMap;

public class ContentHeadersImpl implements ContentHeaders {

    private final static Map<String,ContentHeader> EMPTY_HEADERS = ImmutableMap.of();
    private final static Map<String,ContentHeader> DEFAULT_HEADERS = ImmutableMap.of(
                RFC2045.CONTENT_TYPE.getName(), ContentType.DEFAULT,
                RFC2045.CONTENT_DISPOSITION.getName(), ContentDisposition.DEFAULT,
                RFC2045.CONTENT_TRANSFER_ENCODING.getName(), ContentTransferEncoding.DEFAULT);
    
    private final Map<String,ContentHeader> headers;

    public ContentHeadersImpl(Map<String,ContentHeader> headers) {
        if (headers == null) {
            this.headers = EMPTY_HEADERS;
        } else {
            this.headers = headers;
        }
    }

    public ContentHeadersImpl() {
        this(EMPTY_HEADERS);
    }
    
    private ContentHeader get(RFC2045 key) {
        ContentHeader value = headers.get(key.getName());
        if (value == null) {
            value = DEFAULT_HEADERS.get(key.getName());
        }
        return value;
    }
    
    public String getContentType() {
        
        ContentHeader ch = get(RFC2045.CONTENT_TYPE);        
        // TODO: Encapsulate this.
        return ch.getType() + "/" + ch.getSubType();
    }
    
    public String toString() {
        Collection<String> lines = new ArrayList<String>();
        for (ContentHeader h : headers.values()) {
            lines.add(h.toString());
        }
        
        if (lines.size() > 0) {
            lines.add("");
        }

        return Strings.join(lines, "\r\n");
    }

    public String getBoundary() {
        ContentType contentType = (ContentType) get(RFC2045.CONTENT_TYPE);
        if (contentType != null) {
            return contentType.getBoundary();
        } else {
            return null;
        }
    }
}
